import { paginatedResponse, errorResponse } from "server/utils/response";
import { Projects } from "server/models/Project";

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = parseInt(query.page as string) || 1;
    const pageSize = Math.min(parseInt(query.pageSize as string) || 10, 50);
    const search = query.search as string;
    const status = query.status as string;
    const category = query.category as string;
    const featured = query.featured as string;
    const sortBy = (query.sortBy as string) || "created_at";
    const sortOrder = (query.sortOrder as string) || "desc";

    // 使用数据库查询
    const result = await Projects.getProjects({
      page,
      pageSize,
      search,
      status,
      category,
      featured,
      sortBy,
      sortOrder,
    });

    return paginatedResponse(
      result.projects,
      {
        page,
        pageSize,
        total: result.total,
        totalPages: Math.ceil(result.total / pageSize),
      },
      "获取项目列表成功"
    );
  } catch (error) {
    console.error("获取项目列表失败:", error);
    return errorResponse(
      "获取项目列表失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
